<template>
  <e-group :value="editorValue"
    :gutter="0"
    @add="handleAddressAdd"
    @remove="handleAddressRemove">
    <template slot-scope="scope">
      <cascader-address :ref="`cascaderAdressRef${scope.index}`" v-model="editorValue[scope.index]" @change="handleAdressChange(scope.index, $event)"/>
    </template>
  </e-group>
</template>
<script>
  /**
   * 地址级联 + 多选区
   */
  import EGroup from '@e-ui/Group'
  import CascaderAddress from './CascaderAddress' // 地址区多选
  export default {
    components: {
      EGroup,
      CascaderAddress
    },
    props: {
      value: {
        type: Array
      }
    },
    data () {
      return {
        editorValue: this.value,
        editorState: [true]
      }
    },
    methods: {
      handleAddressAdd () {
        this.editorValue.push([])
        this.editorState.push(true)
      },
      handleAddressRemove (index) {
        this.editorValue.splice(index, 1)
        this.editorState.splice(index, 1)
        this.$nextTick(_ => {
          let endIndex = this.editorValue.length
          for (let i = index; i < endIndex; i++) {
            this.$refs[`cascaderAdressRef${i}`].initAddressData() // 手动更新
          }
        })
      },
      handleAdressChange (index, {value, valueTexts, addressHead = {}}) {
        /**
         * @param{addressHead}用来处理如果其provinceId存在则为选择了一半，这个是要提示选择完整地址，如果没有则为默认值（无需处理）
         * editorState用来记录每个地址的状态，是否需要提示，如果有一个存在需要提示完整地址则都需要提示
         * isOk用来定义是更新还是删除  删除则为提示
         */
        let resultData = { index }
        this.editorState[index] = Boolean(value || !addressHead.provinceId)
        let isOk = !this.editorState.filter(k => !k).length // 是否存在不完整的项
        if (value) {
          // 地址区多选
          let tempValue = []
          let tempValueText = []
          // this.editorValue[index] = value ? [value[0], valueTexts[0]] : ['', '']
          this.editorValue[index] = [value[0], valueTexts[0]]
          this.editorValue.forEach(item => {
            if (item[0]) {
              tempValue = tempValue.concat(JSON.parse(item[0])) // code
              tempValueText = tempValueText.concat(JSON.parse(item[1])) // text
            }
          })
          resultData.value = tempValue
          resultData.valueTexts = tempValueText
        }
        // 此处的值需要对于formItem里面的值
        resultData.type = isOk ? 'update' : 'delete'
        this.$emit('change', resultData)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .cascader-wrapper{
    width: 578px;
  }
</style>
